package com.catsic.base;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

/**
 * 
 * @author yangyd
 *
 */
public abstract class BaseServiceImpl<T , PK extends Serializable> implements BaseService<T, PK>{

	public static final String DEFAUL_FIRST_SORT = "createTime";
	
	/**
	 * 泛型注入
	 */
	@Autowired  
    protected BaseDao<T,PK> baseDao;
	
	/**
	 * 创建实体
	 * @see com.catsic.base.BaseService#add(java.lang.Object)
	 */
	@Override
	public T add(T entity) {
		return baseDao.save(entity);
	}
	
	 /**
	 * save:保存实体集合
	 * @author yangyd 
	 * @param entities
	 * @return
	 */
	@Override
	public <S extends T> List<S> save(Iterable<S> entities) {
		return baseDao.save(entities);
	}
	
	/**
	 * 根据主键删除实体
	 * @see com.catsic.base.BaseService#delete(java.io.Serializable)
	 */
	@Override
	public void delete(PK id) {
		baseDao.delete(id);
	}
	
	/**
	 * 删除实体
	 * @see com.catsic.base.BaseService#delete(java.lang.Object)
	 */
	@Override
	public void delete(T entity) {
		baseDao.delete(entity);
	}
	
	/**
	 * 删除实体集合，如List、Set
	 * @see com.catsic.base.BaseService#delete(java.lang.Iterable)
	 */
	@Override
	public void delete(Iterable<? extends T> entities) {
		baseDao.delete(entities);
	}
	
	/**
	 * 更新实体
	 * @see com.catsic.base.BaseService#update(java.lang.Object)
	 */
	@Override
	public void update(T entity) {
		baseDao.save(entity);
	}
	
	/**
	 * 根据主键获得实体
	 * @see com.catsic.base.BaseService#getById(java.io.Serializable)
	 */
	@Override
	public T getById(PK id) {
		return baseDao.findOne(id);
	}
	
	
	/**
	 * 根据ID查看实体类是否存在，true 存在、false 不存在
	 * @see com.catsic.base.BaseService#exists(java.io.Serializable)
	 */
	@Override
	public boolean exists(PK id) {
		return baseDao.exists(id);
	}
	
	
	/**
	 * 返回所有实体
	 * @see com.catsic.base.BaseService#findAll()
	 */
	@Override
	public List<T> findAll() {
		return baseDao.findAll();
	}
	
	
	/**
	 * 根据给定的ID集合，返回实体List集合
	 * @see com.catsic.base.BaseService#findAll(java.lang.Iterable)
	 */
	@Override
	public List<T> findAll(Iterable<PK> ids) {
		return baseDao.findAll(ids);
	}
	
	public Sort sort(Direction direction,String field){
		Sort sort = new Sort(direction, field);
/*		Sort sort = new Sort(Sort.Direction.DESC, field)
	 	   .and(new Sort(Sort.Direction.ASC, "createName"));*/
		return sort;
	}
}
